package com.example.h5shell.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.Telephony;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

public class SmsHelper {

    private Context context;

    public SmsHelper(Context context) {
        this.context = context;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public List<Sms> readSmsMessages() {
        List<Sms> smsList = new ArrayList<>();

        // 检查是否有读取短信的权限
        if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {

            // 所以我们假设权限已经被授予或者这个方法是在具有权限的上下文中调用的。
            return smsList; // 或者抛出一个异常
        }

        Uri uri = Uri.parse("content://sms/");
        String[] projection = new String[]{
                Telephony.Sms._ID,
                Telephony.Sms.ADDRESS,
                Telephony.Sms.BODY,
                Telephony.Sms.DATE
        };

        try (Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    long id = cursor.getLong(cursor.getColumnIndexOrThrow(Telephony.Sms._ID));
                    String address = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
                    String body = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.BODY));
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(Telephony.Sms.DATE));

                    Sms sms = new Sms(id, address, body, date);
                    smsList.add(sms);
                } while (cursor.moveToNext());
            }
        }

        return smsList;
    }

    // 一个简单的Sms类来存储短信信息
    public static class Sms {
        public long id;
        public String address;
        public String body;
        public long date;

        public Sms(long id, String address, String body, long date) {
            this.id = id;
            this.address = address;
            this.body = body;
            this.date = date;
        }
    }
}


